import pickle
import csv

import numpy as np
import tensorflow as tf

if __name__ == "__main__":
    compare_result_path = "tf.math.sign.csv"
    input_dict_list = [
        {"x": np.array([-1, 2, -3], dtype=np.int32)},
        {"x": np.array([-3.4e+307+0.j, -6.32e+307+0.j], dtype=np.complex128)}
    ]

    source_results = []
    follow_results = []

    for input_dict in input_dict_list:
        try:
            with tf.device("/cpu:0"):
                a = tf.math.sign(**input_dict)
                print("CPU output:")
                print(a)
        except Exception as e:
            print("[CPU] Exception occurred~:\n", e)
            a = tf.constant([])
        # Save source output
        source_results.append(a.numpy())

        try:
            with tf.device("/gpu:0"):
                b = tf.math.sign(**input_dict)
                print("GPU output:")
                print(b)
        except Exception as e:
            print("[GPU] Exception occurred~:\n", e)
            b = tf.constant([])
        # Save follow-up output
        follow_results.append(b.numpy())

    # Compare source results and follow-up results
    compare_results = []
    for i in range(len(source_results)):
        a = source_results[i]
        b = follow_results[i]
        if np.allclose(a, b, atol=1.e-2, rtol=1.e-5, equal_nan=True):
            compare_results.append([i, "Consistent"])
        else:
            compare_results.append([i, "Inconsistent", a.shape, a.dtype])
    with open(compare_result_path, "w+", newline="") as f:
        w = csv.writer(f)
        w.writerows(compare_results)



